package com.shoulder.boot.ops.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Slf4j
@Component
public class SSHSocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response
            , WebSocketHandler wsHandler, Map<String, Object> attributes) {
        log.info("SSHSocketInterceptor before handshake");
        String[] uri = request.getURI().getPath().split("/");
        String token = uri[uri.length - 1];
        if (StringUtils.hasText(token)) {
            // 放入属性域
            attributes.put("token", token);
            log.info("SSHSocketInterceptor token {} 握手成功！", token);
            return true;
        }
        log.info("SSHSocketInterceptor token 已失效");
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info("SSHSocketInterceptor token 握手完成 ");
    }
}
